package com.serie402.web.action;

import org.apache.log4j.Logger;

import com.kiss.fw.action.AbstractAction;
import com.kiss.fw.context.ActionContext;
import com.kiss.fw.exceptions.ActionException;
import com.kiss.fw.utils.Util;
import com.serie402.common.delegate.NewsDelegate;
import com.serie402.common.dto.NewsDTO;
import com.serie402.common.dto.page.NewsPageDTO;
import com.serie402.common.utils.Constants;

public final class ArticleAction extends AbstractAction {
	private static final Logger logger = Logger.getLogger(ArticleAction.class);
	
	/**
	 * Validate action request.
	 * 
	 * @param ActionContext _context
	 */
	@Override
	public boolean validate(final ActionContext _context) {
		final String newsId = _context.getRequest().getParameter(Constants.FieldNames.NEWS_ID);
		boolean returnVal = true;
		
		if(Util.isStringEmpty(newsId) || Util.parseInt(newsId, -1) < 1) {
			returnVal = false;
		}
		
		return returnVal;
	}
	
	/**
	 * Execute action.
	 * 
	 * @param ActionContext _context
	 */
	public void execute(ActionContext _context) throws ActionException {
		NewsDTO dto = new NewsDTO(Util.parseInt(_context.getRequest().getParameter(Constants.FieldNames.NEWS_ID), -1));
		NewsPageDTO pageDto = null;
		
		if(_context.isReadAction()) {
			try {
				NewsDelegate.read(dto);
			}
			catch(Exception _exception) {
				handleActionException(logger, "execute", _exception);
			}
			
			if(dto.getNews() != null) {
				// prepare news page
				pageDto = new NewsPageDTO();
				pageDto.setNews(dto.getNews());
				pageDto.setWindowTitle(dto.getNews().getTitle());
				pageDto.setPageTitle(dto.getNews().getTitle());
			}
			else {
				throw com.kiss.fw.utils.Constants.Exceptions.ACTION_404_EXCEPTION;
			}
		}
		
		_context.setRequestAttribute(Constants.Mappings.ARTICLE_DTO, pageDto);
	}
	
	@Override
	public void create(ActionContext _context) throws ActionException {
	}
	
	@Override
	public void read(ActionContext _context) throws ActionException {
	}
	
	@Override
	public void update(ActionContext _context) throws ActionException {
	}
	
	@Override
	public void delete(ActionContext _context) throws ActionException {
	}
	
	@Override
	public void search(ActionContext _context) throws ActionException {
	}
	
	@Override
	public void browse(ActionContext _context) throws ActionException {
	}
}